#include "driver_mq2.h"


static ADC_HandleTypeDef MQ2_ADC = {0};

void MQ2_ADC_Init(void)
{
    MQ2_ADC.Instance = ADC1;
    MQ2_ADC.Init.ContinuousConvMode = ENABLE;
    MQ2_ADC.Init.DataAlign = ADC_DATAALIGN_RIGHT;
    MQ2_ADC.Init.DiscontinuousConvMode  = DISABLE;
    MQ2_ADC.Init.ExternalTrigConv = ADC_SOFTWARE_START;
    MQ2_ADC.Init.NbrOfConversion = 1;
    MQ2_ADC.Init.NbrOfDiscConversion = DISABLE;
    MQ2_ADC.Init.ScanConvMode = DISABLE;
    HAL_ADC_Init(&MQ2_ADC);
    HAL_ADCEx_Calibration_Start(&MQ2_ADC);
}


void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
{
    if(hadc->Instance == ADC1)
    {
        RCC_PeriphCLKInitTypeDef  PeriphClkInit = {0};
        __ADC1_CLK_ENABLE();
        PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
        PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
        HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
        
        GPIO_InitTypeDef  MQ2GpioInit = {0};
        __HAL_RCC_GPIOA_CLK_ENABLE();   
        MQ2GpioInit.Mode = GPIO_MODE_ANALOG;
        MQ2GpioInit.Pin = MQ2_Pin;
        HAL_GPIO_Init(MQ2_GPIO_Port, &MQ2GpioInit);
        
        DMA_HandleTypeDef MQ2DmaInit = {0};
        __HAL_RCC_DMA1_CLK_ENABLE();
        MQ2DmaInit.Instance = DMA1_Channel1;
        MQ2DmaInit.Init.Direction = DMA_PERIPH_TO_MEMORY;
        MQ2DmaInit.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
        MQ2DmaInit.Init.MemInc = DMA_MINC_ENABLE;
        MQ2DmaInit.Init.Mode = DMA_CIRCULAR;
        MQ2DmaInit.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
        MQ2DmaInit.Init.PeriphInc = DMA_PINC_DISABLE;
        MQ2DmaInit.Init.Priority = DMA_PRIORITY_VERY_HIGH;
        HAL_DMA_Init(&MQ2DmaInit);
        __HAL_LINKDMA(&MQ2_ADC, DMA_Handle, MQ2DmaInit);            
    }    
}


void MQ2_ADC_CHANNEL_Conf(uint32_t Channel, uint32_t Rank, uint32_t SamplingTime)
{
    ADC_ChannelConfTypeDef MQ2AdcChannelConf = {0};
    MQ2AdcChannelConf.Channel = Channel;
    MQ2AdcChannelConf.Rank = Rank;
    MQ2AdcChannelConf.SamplingTime = SamplingTime;
    HAL_ADC_ConfigChannel(&MQ2_ADC, &MQ2AdcChannelConf);
}
   

void MQ2_ADC_GetValue(uint32_t *pData, uint32_t Length)
{
    MQ2_ADC_CHANNEL_Conf(ADC_CHANNEL_5, ADC_REGULAR_RANK_1, ADC_SAMPLETIME_13CYCLES_5);
    HAL_ADC_Start_DMA(&MQ2_ADC, pData, Length);
}

